/**
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at
 * <p> http://www.apache.org/licenses/LICENSE-2.0 <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations 
 * under the License.
 */
package org.hilo.boot.core.code;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.hilo.boot.core.UT;

import org.jretty.util.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * <p>
 * 模板引擎抽象类
 * </p>
 *
 * @author hubin, zollty
 * @since 2018-01-10
 */
public abstract class AbstractTemplateEngine {

    protected static final Logger logger = LoggerFactory.getLogger("");
    /**
     * 配置信息
     */
    private ConfigBuilder configBuilder;

    /**
     * <p>
     * 模板引擎初始化
     * </p>
     */
    public AbstractTemplateEngine init(ConfigBuilder configBuilder) {
        this.configBuilder = configBuilder;
        return this;
    }

    /**
     * <p>
     * 输出 java xml 文件
     * </p>
     */
    public AbstractTemplateEngine batchOutput() {
        try {
            ServiceInfo serviceInfo = getConfigBuilder().getServiceInfo();
            String templatePath = getConfigBuilder().getServiceTmplPath();
            
            String baseDir = UT.Path.connectPaths(getConfigBuilder().getBaseDir(),
                    UT.Str.replace(serviceInfo.getPackageName(), ".", "/") + "/"
                    + serviceInfo.getDtoPath());
            
            String filePath = baseDir + "/api/" + serviceInfo.getClassName() + ".java";
            
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("entity", serviceInfo);
            
            writeFile(objectMap, templatePath, filePath);
            
            EntityInfo entityInfo = getConfigBuilder().getParamsInfo();
            
            baseDir = UT.Path.connectPaths(getConfigBuilder().getBaseDir(),
                    UT.Str.replace(entityInfo.getPackageName(), ".", "/") + "/"
                    + entityInfo.getDtoPath());
            
            templatePath = getConfigBuilder().getEntityTmplPath();
            filePath = baseDir + "/dto/" + entityInfo.getClassName() + ".java";
            
            objectMap = new HashMap<>();
            objectMap.put("entity", entityInfo);
            
            writeFile(objectMap, templatePath, filePath);
            
            entityInfo = getConfigBuilder().getResultsInfo();
            templatePath = getConfigBuilder().getEntityTmplPath();
            filePath = baseDir + "/dto/" + entityInfo.getClassName() + ".java";
            
            objectMap = new HashMap<>();
            objectMap.put("entity", entityInfo);
            
            writeFile(objectMap, templatePath, filePath);
            
        } catch (Exception e) {
            logger.error("无法创建文件，请检查配置信息！", e);
        }
        return this;
    }

    
    protected void writeFile(Map<String, Object> objectMap, 
            String templatePath, String outputFile) throws Exception {
        File f = new File(outputFile);
        if(!f.exists()) {
            UT.File.forceMkdirParent(f);
        } else if(!getConfigBuilder().isFileOverride()) {
            outputFile = getNewPath(outputFile);
        }
        UT.File.forceMkdirParent(new File(outputFile));
        this.writer(objectMap, templatePath, outputFile);
//        if (this.isCreate(outputFile)) {
//            this.writer(objectMap, templatePath, outputFile);
//        } else {
//            logger.warn("文件已存在:" + outputFile);
//        }
    }


    /**
     * <p>
     * 将模板转化成为文件
     * </p>
     *
     * @param objectMap    渲染对象 MAP 信息
     * @param templatePath 模板文件
     * @param outputFile   文件生成的目录
     */
    public abstract void writer(Map<String, Object> objectMap, 
                String templatePath, String outputFile) throws Exception;


    /**
     * <p>
     * 打开输出目录
     * </p>
     */
    public void open() {
        try {
            String osName = System.getProperty("os.name");
            if (osName != null) {
                if (osName.contains("Mac")) {
                    Runtime.getRuntime().exec("open " + getConfigBuilder().getBaseDir());
                } else if (osName.contains("Windows")) {
                    Runtime.getRuntime().exec("cmd /c start " + getConfigBuilder().getBaseDir());
                } else {
                    logger.debug("文件输出目录:" + getConfigBuilder().getBaseDir());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static String getNewPath(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return UT.Path.normalPath(filePath);
        } else {
            String tpath = stripFileExtensionFromPath(filePath);
            int extIndex = tpath.lastIndexOf("-");
            int n = 1;
            if (extIndex > 0) {
                String end = tpath.substring(extIndex + 1);
                try {
                    n = Integer.parseInt(end) + 1;
                    tpath = tpath.substring(0, extIndex);
                } catch (Exception e) {
                    // ignore...
                }
            }
            String ext = UT.Path.getFilenameExtension(filePath);
            if (ext != null) {
                return getNewPath(tpath + "-" + n + "." + ext);
            } else {
                return getNewPath(tpath + "-" + n);
            }
        }
    }
    
    public static String stripFileExtensionFromPath(String path) {
        if (null == path) {
            return null;
        }
        int extIndex = path.lastIndexOf(Const.DOT);
        if (extIndex == -1) {
            return path;
        }
        String path2 = path.replace(Const.WINDOWS_FOLDER_SEPARATOR, Const.FOLDER_SEPARATOR);
        int folderIndex = path2.lastIndexOf(Const.FOLDER_SEPARATOR);
        return folderIndex > extIndex ? path2 : path2.substring(0, extIndex);
    }

//    /**
//     * 检测文件是否存在
//     *
//     * @return 是否
//     */
//    protected boolean isCreate(String filePath) {
//        File file = new File(filePath);
//        boolean exist = file.exists();
//        if (!exist) {
//            this.mkDir(file.getParentFile());
//            return true;
//        } else {
//            return getConfigBuilder().isFileOverride();
//        }
//    }
//
//    protected void mkDir(File file) {
//        if (null != file) {
//            if (file.getParentFile().exists()) {
//                if (!file.exists()) {
//                    file.mkdir();
//                    logger.debug("创建目录： [" + file.getAbsolutePath() + "]");
//                }
//            } else {
//                mkDir(file.getParentFile());
//                if (!file.exists()) {
//                    file.mkdir();
//                    logger.debug("创建目录： [" + file.getAbsolutePath() + "]");
//                }
//            }
//        }
//    }


    public ConfigBuilder getConfigBuilder() {
        return configBuilder;
    }

    public AbstractTemplateEngine setConfigBuilder(ConfigBuilder configBuilder) {
        this.configBuilder = configBuilder;
        return this;
    }
}
